﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	SmartLib
//  File name:	Class1.cs
//  Developer:	Igor Solomatov
//  Created:	04.11.2012
// 
// -------------------- iSharePoint -------------------- //

using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace Smart.Iterators
{
	public abstract class Iterator<TSource> : IEnumerable<TSource>, IEnumerator<TSource>
	{
		private readonly int _threadId;
		protected int State;
		protected TSource CurrentValue;

		public TSource Current
		{
			get { return CurrentValue; }
		}

		object IEnumerator.Current
		{
			get { return Current; }
		}

		protected Iterator()
		{
			_threadId = Thread.CurrentThread.ManagedThreadId;
		}

		public abstract Iterator<TSource> Clone();

		public virtual void Dispose()
		{
			CurrentValue = default(TSource);
			State = -1;
		}

		public IEnumerator<TSource> GetEnumerator()
		{
			if (_threadId == Thread.CurrentThread.ManagedThreadId && State == 0)
			{
				State = 1;
				return this;
			}

			var iterator = Clone();
			iterator.State = 1;
			return iterator;
		}

		public abstract bool MoveNext();

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		void IEnumerator.Reset()
		{
			State = 1;
			CurrentValue = default(TSource);

			ResetImpl();
		}

		protected abstract void ResetImpl();
	}
}